/*
 * @Description:
 * @Author: Mr.Wen
 * @Version: v1.0.0
 * @Date: 2023-12-26 17:10:13
 * @LastEditors: Mr.Wen - 文先生
 * @LastEditTime: 2024-01-03 14:54:42
 */

require('module-alias/register');
require('@/utils');

const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs');
const expressSwagger = require('express-swagger-generator');
const { jwtCheck } = require('@/utils/jwt');

const { PORT, HOST, SERVICE_NAME } = require('./utils/settings');

const app = new express();

expressSwagger(app)({
  swaggerDefinition: {
    info: {
      title: 'API 文档',
      version: '2.0.0',
      description: 'API 文档描述',
    },
    host: 'localhost:3000',
    basePath: '/',
    produces: ['application/json', 'application/xml'],
    schemes: ['http', 'https'],
  },
  securityDefinitions: {
    JWT: {
      type: 'apiKey',
      in: 'header',
      name: 'Authorization',
      description: '',
    },
  },
  basedir: __dirname,
  files: ['./routes/*.js'],
  route: {
    url: '/api-docs',
    docs: '/swagger.json',
  },
});

app.use(jwtCheck); // 验证TOKEN - 注册全局中间件

app.use(cors()); // CORS 允许跨域请求

app.use(express.json()); // 请求体参数是JSON结构 {name:Tom,pwd:123} 解析application/json格式数据
app.use(express.urlencoded({ extended: false })); // 请求体参数是 name=Tom&pwd=123 解析application/x-www-form-urlencoded格式数据

app.use('/public', express.static(path.join('./', 'public'))); // 相对路径
app.use('/klein', express.static(path.resolve('./', 'public/klein-web'))); // 绝对路径

// 注册路由对象
const serveName = SERVICE_NAME.split('-').slice(0, -1).join('-') + '-web';
const servePath = path.join(__dirname, `project-routes/${serveName}`);
const routeArraryApi = fs.readdirSync(servePath).map((item) => {
  return require(`${servePath}/${item}`);
});
app.use(`/${SERVICE_NAME}`, routeArraryApi);

// TODO 错误级处理中间件注册(必须在所有路由之后)
app.use((err, req, res, next) => {
  // 设置本地，提供开发环境错误信息
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  // res.json({
  //   message: err.message,
  //   error: err,
  // });
  res.render('error');
  next();
});

app.listen(
  PORT,
  HOST,
  () =>
    console.log(
      '\x1B[32m%s\x1B[0m',
      `The Server Is Running At http://${HOST}:${PORT}`
    )
  // console.log('The Server Is Running On http://%s:%s', HOST, PORT));
);
